import { ChatContext } from '@/app/chat-context';
import { apiInterceptors, getAppInfo } from '@/client/api';
import ChatContent from '@/new-components/chat/content/ChatContent';
import { CopilotChatContext } from './index';
import { IApp } from '@/types/app';
import { IChatDialogueMessageSchema } from '@/types/chat';
import { STORAGE_INIT_MESSAGE_KET, getInitMessage } from '@/utils';
import { useAsyncEffect } from 'ahooks';
import { cloneDeep } from 'lodash';
import { VerticalAlignBottomOutlined, VerticalAlignTopOutlined } from '@ant-design/icons';
import React, { useContext, useEffect, useMemo, useRef, useState,useImperativeHandle } from 'react';
import { v4 as uuid } from 'uuid';
import { Card, Image, Space, Tag, Button } from 'antd';

const ChatContentCompletion: React.FC = ({chatId}) => {
  const { Meta } = Card;
  localStorage.setItem('CHAT_FROM', 'copilot');
  const scrollRef = useRef<HTMLDivElement>(null);
  const [isScrollToTop, setIsScrollToTop] = useState<boolean>(false);
  const [showScrollButtons, setShowScrollButtons] = useState<boolean>(false);
  const [isAtTop, setIsAtTop] = useState<boolean>(true);
  const [isAtBottom, setIsAtBottom] = useState<boolean>(false);
 
  const { currentDialogInfo, model } = useContext(ChatContext);
  const {
    history,
    handleChat,
    refreshDialogList,
    resourceValue,
    appInfo,
    setAppInfo,
    setModelValue,
    setTemperatureValue,
    setMaxNewTokensValue,
    setResourceValue,
    canAbort,
    setCanAbort
  } = useContext(CopilotChatContext);

  const showMessages = useMemo(() => {
    const tempMessage: IChatDialogueMessageSchema[] = cloneDeep(history);
    return tempMessage
      .filter(item => ['view', 'human'].includes(item.role))
      .map(item => {
        return {
          ...item,
          key: uuid(),
        };
      });
  }, [history]);

  useAsyncEffect(async () => {
    const initMessage = getInitMessage();
    if (initMessage && initMessage.id === chatId) {
      const [, res] = await apiInterceptors(
        getAppInfo({
          ...currentDialogInfo,
        }),
      );
      if (res) {
        const paramKey: string[] = res?.param_need?.map(i => i.type) || [];
        const resModel = res?.param_need?.filter(item => item.type === 'model')[0]?.value || model;
        const temperature = res?.param_need?.filter(item => item.type === 'temperature')[0]?.value || 0.6;
        const maxNewTokens = res?.param_need?.filter(item => item.type === 'max_new_tokens')[0]?.value || 4000;
        const resource = res?.param_need?.filter(item => item.type === 'resource')[0]?.bind_value;
        setAppInfo(res || ({} as IApp));
        setTemperatureValue(temperature || 0.6);
        setMaxNewTokensValue(maxNewTokens || 4000);
        setModelValue(resModel);
        setResourceValue(resource);
        await handleChat(initMessage.message, {
          app_code: res?.app_code,
          model_name: resModel,
          ...(paramKey?.includes('temperature') && { temperature }),
          ...(paramKey?.includes('max_new_tokens') && { max_new_tokens: maxNewTokens }),
          ...(paramKey.includes('resource') && {
            select_param: typeof resource === 'string' ? resource : JSON.stringify(resource),
          }),
        });
        await refreshDialogList();
        localStorage.removeItem(STORAGE_INIT_MESSAGE_KET);
      }
    }
  
  }, [chatId, currentDialogInfo]);
  
    const handleScroll = () => {
      if (!scrollRef.current) return;
  
      const container = scrollRef.current;
      const scrollTop = container.scrollTop;
      const scrollHeight = container.scrollHeight;
      const clientHeight = container.clientHeight;
      const buffer = 20; // Small buffer for better UX
  
      // Check if we're at the top
      setIsAtTop(scrollTop <= buffer);

      // Check if we're at the bottom
      setIsAtBottom(scrollTop + clientHeight >= scrollHeight - buffer);
  
      // Header visibility
      if (scrollTop >= 42 + 32) {
        setIsScrollToTop(true);
      } else {
        setIsScrollToTop(false);
      }
  
      // Show scroll buttons when content is scrollable
      const isScrollable = scrollHeight > clientHeight;
      setShowScrollButtons(isScrollable);
    };
  
    useEffect(() => {
      if (scrollRef.current) {
        scrollRef.current.addEventListener('scroll', handleScroll);
  
        // Check initially if content is scrollable
        const isScrollable = scrollRef.current.scrollHeight > scrollRef.current.clientHeight;
        setShowScrollButtons(isScrollable);
      }
  
      return () => {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        scrollRef.current && scrollRef.current.removeEventListener('scroll', handleScroll);
      };
    }, []);
  
    const scrollToTop = () => {
      if (scrollRef.current) {
        scrollRef.current.scrollTo({
          top: 0,
          behavior: 'smooth',
        });
      }
    };
  
    const scrollToBottom = () => {
      if (scrollRef.current) {
        scrollRef.current.scrollTo({
          top: scrollRef.current.scrollHeight,
          behavior: 'smooth',
        });
      }
    };

    useEffect(() => {
      if (showMessages.length >= 2) {
        let lastUserIdx = -1;
        for (let i = showMessages.length - 1; i >= 0; i--) {
          if (showMessages[i].role === 'human') {
            lastUserIdx = i;
            break;
          }
        }
        if (lastUserIdx !== -1 && lastUserIdx < showMessages.length - 1) {
          const lastQuestion = showMessages[lastUserIdx];
          // const lastAnswer = showMessages[lastUserIdx + 1];
          // 存到 sessionStorage
          sessionStorage.setItem(
            'history_last_qa',
            JSON.stringify({ question: lastQuestion })
          );
        }
      }
    }, [showMessages]);
  
  return (
    <div className='flex flex-1 overflow-hidden relative'>
      <div ref={scrollRef} className='h-full w-full mx-auto overflow-y-auto'>
        { !!appInfo?.recommend_questions?.length && <Card className='m-5'>
          <Meta
            avatar={<Image src='/chat-excel/ai-copilot.png' className='mt-1' preview={false} width={15} height={18} />}
            title="推荐问题"        
          />
          
          {appInfo.recommend_questions.map((item, index) => (
              <Button  disabled={canAbort}
                key={item.id}                      
                className='w-full mt-3 p-2'
                onClick={async () => {
                  setCanAbort(true)
                  handleChat(item?.question || '', {
                    app_code: appInfo.app_code,
                    conv_uid: chatId || '',
                    temperature: 0.6,
                    maxNewTokens: 4000,
                    select_param: resourceValue.toString()
                  });              
                }}
              >
                {item.question}
              </Button>
            ))}               
        </Card>
      }
        {!!showMessages.length &&
          showMessages.map((content, index) => {
            return (
              <ChatContent
                key={index}
                content={content}            
              />
            );
          })}
      </div>
          
      {showScrollButtons && (
        <div className='absolute left-1 bottom-24 flex flex-col gap-2'>
          {!isAtTop && (
            <button
              onClick={scrollToTop}
              className='w-8 h-8 bg-white dark:bg-[rgba(255,255,255,0.2)] border border-gray-200 dark:border-[rgba(255,255,255,0.2)] rounded-full flex items-center justify-center shadow-md hover:shadow-lg transition-shadow'
              aria-label='Scroll to top'
            >
              <VerticalAlignTopOutlined className='text-[#525964] dark:text-[rgba(255,255,255,0.85)]' />
            </button>
          )}
          {!isAtBottom && (
            <button
              onClick={scrollToBottom}
              className='w-8 h-8 bg-white dark:bg-[rgba(255,255,255,0.2)] border border-gray-200 dark:border-[rgba(255,255,255,0.2)] rounded-full flex items-center justify-center shadow-md hover:shadow-lg transition-shadow'
              aria-label='Scroll to bottom'
            >
              <VerticalAlignBottomOutlined className='text-[#525964] dark:text-[rgba(255,255,255,0.85)]' />
            </button>
          )}
        </div>
      )}
    </div>
  );
};

export default ChatContentCompletion;
